////
////  XMHomeViewController.m
////  XMJJ_zml
////
////  Created by apple on 2025/5/7.

#import "XMHomeViewController.h"
#import "XMLoginOtherPhoneController.h"
#import "CityViewController.h"
#import "ZMYCommend.h"
#import "XMHAreaModel.h"
#import "XMHomeDetailViewController.h"
#import "XMCSConfiguration.h"
#import "XMHomeView.h"
#import "XMNetwork+home.h"
#import "XMNetwork+mine.h"
#import "ZMSearchViewController.h"
#import "XMAreaSelectViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "XMMeetDetailViewController.h"
#import "XMMeetSearchViewController.h"

@interface XMHomeViewController ()<XMHomeViewDelegate, CityViewControllerDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) XMHomeView *homeView;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *geocoder;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) XMCSConfiguration *config;

@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

@end


@implementation XMHomeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavigationBar:YES animated:YES];
    [self.locationManager startUpdatingLocation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.locationManager stopUpdatingLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
}

- (void)creatUI {
    [self.view addSubview:self.homeView];
    _page = 1;
    _selectIndex = 1;
    self.config = [[XMCSConfiguration alloc] init];
    [self getHomeDataWithType:_selectIndex];
}

- (void)getHomeDataWithType:(NSInteger)type {
    XMWeakSelf;
    [_Network getHomeDataWithType:type
                             page:[NSString stringWithFormat:@"%ld", _page]
                        longitude:[NSString stringWithFormat:@"%f", _coordinate.longitude]
                         latitude:[NSString stringWithFormat:@"%f", _coordinate.latitude]
                          success:^(id  _Nonnull responseObject) {
        NSArray *commandModelArr = [NSArray yy_modelArrayWithClass:[ZMYCommend class] json:[responseObject safeArrayForKey:@"data"]];
        [weakSelf.homeView setContentWithMeetModelArr:commandModelArr page:weakSelf.page];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//获取区域信息
- (void)getAreaList {
    XMWeakSelf;
    [_Network getAreaListSuccess:^(id  _Nonnull responseObject) {
        NSArray *areaModelArr = [NSArray yy_modelArrayWithClass:[XMHAreaModel class] json:responseObject[@"data"]];
        XMAreaSelectViewController *areaSelectVC = [[XMAreaSelectViewController alloc] init];
        areaSelectVC.areaModelArr = areaModelArr;
        areaSelectVC.selectBlock = ^(NSString * _Nonnull areaStr, NSString * _Nonnull areaId) {
            NSString *city = [areaStr componentsSeparatedByString:@"-"][1];
            [weakSelf.homeView setLocation:city];
            [weakSelf.geocoder geocodeAddressString:areaStr completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                CLPlacemark *placemark = [placemarks firstObject];
                weakSelf.coordinate = placemark.location.coordinate;
                NSLog(@"%@", error);
            }];
        };
        XMBaseNavigationController *areaNVC = [[XMBaseNavigationController alloc] initWithRootViewController:areaSelectVC];
        areaNVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [weakSelf presentViewController:areaNVC animated:YES completion:nil];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - Delegate
- (void)tabSelectWithIndex:(NSInteger)selectIndex {
    if (selectIndex == 0) {
        XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
        if (userModel && userModel.refreshToken.length > 0) {
            
        }
        else {
            XMLoginOtherPhoneController *loginVC = [[XMLoginOtherPhoneController alloc] init];
            loginVC.hidesBottomBarWhenPushed = YES;
            XMBaseNavigationController *loginNVC = [[XMBaseNavigationController alloc] initWithRootViewController:loginVC];
            [self presentViewController:loginNVC animated:YES completion:nil];
            return;
        }
    }
    else if (selectIndex == 2) {
        if (_coordinate.longitude == 0) {
            [MBProgressHUD showError:@"请开启位置权限"];
            return;
        }
        else {
            
        }
    }
    [self getHomeDataWithType:selectIndex];
}

- (void)refreshData {
    self.page = 1;
    [self getHomeDataWithType:_selectIndex];
}

- (void)loadMore {
    self.page += 1;
    [self getHomeDataWithType:_selectIndex];
}

//搜索
- (void)searchAction {
    XMMeetSearchViewController *searchVC = [[XMMeetSearchViewController alloc] init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
//    ZMSearchViewController * searchVc = [ZMSearchViewController new];
//    // 添加自定义转场动画
//    searchVc.hidesBottomBarWhenPushed = YES;
//    CATransition *transition = [CATransition animation];
//    transition.duration = 0.4;
//    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
//    transition.type = kCATransitionPush;
//    transition.subtype = kCATransitionFromRight;
//    [self.navigationController.view.layer addAnimation:transition forKey:nil];
//    [self.navigationController pushViewController:searchVc animated:NO];
}

//查看详情
- (void)checkDetailWithProdId:(NSString *)prodId {
    XMMeetDetailViewController * detailVC = [XMMeetDetailViewController new];
    detailVC.hidesBottomBarWhenPushed = YES;
    detailVC.serviceId = prodId;
    [self.navigationController pushViewController:detailVC animated:YES];
}

//地址选择
- (void)addressSelectAction {
    [self getAreaList];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations firstObject];
    _coordinate = location.coordinate;
    XMWeakSelf;
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placeMark = [placemarks firstObject];
        [weakSelf.homeView setLocation:placeMark.locality];
        NSLog(@"%@", placeMark.locality);
    }];
    [manager stopUpdatingLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"定位失败");
}

- (void)viewController:(CityViewController *)viewController didSelectCity:(XMCSBaseInfoModel *)model {
    
}

#pragma mark - Init
- (XMHomeView *)homeView {
    if (!_homeView) {
        _homeView = [[XMHomeView alloc] initWithFrame:self.view.bounds];
        _homeView.delegate = self;
    }
    return _homeView;
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 1000.0f;
        _locationManager.delegate = self;
        [_locationManager requestWhenInUseAuthorization];
    }
    return _locationManager;
}

- (CLGeocoder *)geocoder {
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

@end
